package com.chenjt.minio.file;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2021/11/5 15:35
 */
@Component
public class FileUtils {


    @Autowired
    private MinioClient minioClient;



    /**
     * 附件上传
     * @param bucketName   菜篮子名称
     * @param objectName   附件上传路径（20210515/test.jpg）
     * @param data         文件字节数组
     * @throws Exception
     */
    public void putObject(String bucketName,String objectName,byte[] data) throws Exception{

        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } else {
            System.out.println("Bucket 'asiatrip' already exists.");
        }


        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                        new ByteArrayInputStream(data), data.length, -1)
                        .build());


    }

    /**
     * 删除目录及其目录下的所有文件
     * @param bucketName 菜篮子名称（chuanbo-picture）
     * @param objectName 目录或文件名
     * @throws Exception
     */
    public void removeObject(String bucketName,String objectName) throws Exception {

        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    }

}
